package com.mashibing.controller;

import com.alibaba.fastjson.JSONObject;
import com.mashibing.bean.TblUserRecord;
import com.mashibing.returnJson.Permission;
import com.mashibing.returnJson.Permissions;
import com.mashibing.returnJson.ReturnObject;
import com.mashibing.returnJson.UserInfo;
import com.mashibing.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：13806
 * @date ：2021/10/2
 * @Version: : 1.0
 */
@RestController
@CrossOrigin(origins = {" * "}, allowedHeaders="*")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @RequestMapping("/auth/2step-code")
    public Boolean  stepCode(){
        System.out.println("前端框架自带校验，写不写无所谓");
        return true;
    }
    @RequestMapping("/auth/login")
    public String login(@RequestParam("username") String username , @RequestParam("password") String password , HttpSession session){
        System.out.println(password);
        System.out.println("===="+session);
        TblUserRecord record = loginService.login(username, password);
        record.setToken(record.getUserName());
        session.setAttribute("userRecord",record);
//        record.setToken(record.getUserName());
        ReturnObject returnObject = new ReturnObject(record);
        return JSONObject.toJSONString(returnObject);
    }
    @RequestMapping("user/info")
    public String getInfo(HttpSession session) {
        System.out.println("===="+session);
        TblUserRecord record = (TblUserRecord) session.getAttribute("userRecord");
        //获取权限
        String[] split = record.getTblRole().getRolePrivileges().split("-");
        Permissions permissions = new Permissions();
        List<Permission> permissionList = new ArrayList<>();
        for (String s : split) {
            permissionList.add(new Permission(s));
        }
        permissions.setPermissions(permissionList);
        UserInfo userInfo = new UserInfo(record.getUserName(),permissions);
        return JSONObject.toJSONString(new ReturnObject(userInfo));
    }
}
